package com.app.business.web.business;

import com.app.business.en.Status;
import com.app.business.model.AzProject;
import com.app.business.model.CarLot;
import com.app.business.service.AzProjectService;
import com.app.business.service.CarLotService;
import com.app.system.jpa.PageBean;
import com.app.system.log4j2.LogUtils;
import com.app.system.permission.model.DataDict;
import com.app.system.permission.service.DataDictService;
import com.app.system.utils.CollectionUtils;
import com.app.system.utils.ParamUtils;
import com.app.system.utils.WebUtils;
import com.app.system.utils.dataType.BigDecimalUtils;
import com.app.system.utils.dataType.DateUtils;
import com.app.system.utils.dataType.IntegerUtils;
import com.app.system.utils.dataType.StringUtils;
import com.app.system.utils.exception.Precondition;
import com.app.system.utils.exception.Response;
import com.app.system.utils.page.LayUiUtils;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import freemarker.template.Configuration;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.transaction.Transactional;
import java.util.*;

/**
 * 车位管理
 * Created by lsh on 2019/2/11 14:49.
 *
 * @author lsh
 */
@Controller
@RequestMapping("/business/carLot/*")
public class CarLotController {

    @Resource
    private CarLotService carLotService;
    @Resource
    private DataDictService dataDictService;
    @Resource
    private AzProjectService azProjectService;
    private Logger logger = LogUtils.getBusinessLogger();

    @Autowired
    private Configuration freemarkerConfiguration; // 注入bean，这里是属性注入，推荐构造注入

    /**
     * 住宅房源数据管理列表
     */
    @RequestMapping("carLotList")
    @RequiresPermissions("carLot:carLotList")
    public void carLotList(HttpServletRequest request, ModelMap modelMap) {
        Integer projectId = ParamUtils.getInt(request, "azProjectId", 0);
        AzProject azProject = this.azProjectService.findOne(projectId);
        modelMap.addAttribute("azProject", azProject);
    }

    /**
     * 加载房源信息数据
     *
     * @return
     */
    @RequestMapping("loadCarLotList")
    @ResponseBody
    @RequiresPermissions("carLot:loadCarLotList")
    public Map loadCarLotList(HttpServletRequest request) {
        Integer projectId = ParamUtils.getInt(request, "azProjectId", 0);
        List<Map> listData = Lists.newArrayList();
        PageBean<CarLot> carLotPageBean = this.carLotService.carLotListByProjectId(projectId);
        List<CarLot> carLotList = carLotPageBean.getDatas();
        Map<String, DataDict> houseStatusMap = this.dataDictService.getMapByParentNameForValue("房源状态");
        Map<String, DataDict> carLotTypeMap = this.dataDictService.getMapByParentNameForValue("车位类型");
        if (!CollectionUtils.isEmpty(carLotList)) {
            Map<String, Object> item = null;
            for (CarLot carLot : carLotList) {
                item = null;
                item = Maps.newHashMap();
                item.put("id", carLot.getId());
                item.put("buildNum", StringUtils.getNotNull(carLot.getBuildNum()));
                item.put("houseNum", StringUtils.getNotNull(carLot.getHouseNum()));
                item.put("floor", IntegerUtils.getNotNull(carLot.getFloor()));
                item.put("buildArea", BigDecimalUtils.getNotNullStr(carLot.getBuildArea()));
                item.put("carLotType", StringUtils.dataDictShow(carLotTypeMap.get(carLot.getCarLotType().toString())));
                item.put("houseStatus", carLot.getHouseStatus());
                item.put("houseStatusStr", StringUtils.dataDictShow(houseStatusMap.get(carLot.getHouseStatus().toString())));
                item.put("chooseDate", DateUtils.dateToStringDefault(carLot.getChooseHouseDate()));
                item.put("memo", carLot.getMemo());
                listData.add(item);
            }
        }
        return LayUiUtils.page(carLotPageBean.getTotalCount().intValue(), listData);
    }

    /**
     * 车位信息导出
     */
    @RequestMapping("carLotListExcel")
    @RequiresPermissions("carLot:carLotListExcel")
    public void carLotListExcel(HttpServletRequest request, HttpServletResponse response) {
        Integer projectId = ParamUtils.getInt(request, "azProjectId", 0);
        PageBean<CarLot> carLotPageBean = this.carLotService.carLotExcelListByProjectId(projectId);
        List<CarLot> carLotList = carLotPageBean.getDatas();
        Map<String, DataDict> houseStatusMap = this.dataDictService.getMapByParentNameForValue("房源状态");
        Map<String, DataDict> carLotTypeMap = this.dataDictService.getMapByParentNameForValue("车位类型");
        try {
            // 封装导出数据
            Map data = Maps.newHashMap();
            data.put("carLotList", carLotList);
            data.put("carLotTypeMap", carLotTypeMap);
            data.put("houseStatusMap", houseStatusMap);
            data.put("exportPerson", SecurityUtils.getSubject().getPrincipal());   //导出人姓名
            data.put("exportTime", DateUtils.dateToStringFormat(new Date(), "yyyy-MM-dd HH:mm:ss"));   //导出时间
//            data.put("decisions", exportDecisionList); //第二个worksheet的数据对象
            request.setCharacterEncoding("UTF-8");
            response.setContentType("application/x-download;");
            response.setHeader("Content-disposition", "attachment; filename=" + new String(("车位数据导出.xls").getBytes(), "iso-8859-1"));
            freemarkerConfiguration.getTemplate("/business/carLot/carLotListExcel.ftl").process(data, response.getWriter());
        } catch (Exception e) {
            logger.error("文件下载异常", e);
            e.printStackTrace();
        }
    }

    /**
     * 住宅房源管理
     *
     * @param request
     * @param modelMap
     */
    @RequestMapping("carLotForm")
    @RequiresPermissions("carLot:carLotForm")
    public void carLotForm(HttpServletRequest request, ModelMap modelMap) {
        Integer carLotId = ParamUtils.getInt(request, "carLotId", 0);
        Integer azProjectId = ParamUtils.getInt(request, "azProjectId", 0);

        CarLot carLot = this.carLotService.findOne(carLotId);
        AzProject azProject = azProjectService.findOne(azProjectId);
        carLot = carLot == null ? new CarLot() : carLot;
        Precondition.checkSqdsArguement(azProject != null, "找不到所属安置项目！");

        modelMap.addAttribute("carLot", carLot);
        modelMap.addAttribute("azProject", azProject);
    }


    /**
     * 房源信息保存
     *
     * @param request
     * @return
     */
    @RequestMapping("carLotSave")
    @ResponseBody
    @RequiresPermissions("carLot:carLotSave")
    public Response carLotSave(HttpServletRequest request) {
        Integer carLotId = ParamUtils.getInt(request, "carLotId", 0);
        Integer azProjectId = ParamUtils.getInt(request, "azProjectId", 0);
        CarLot carLot = carLotService.findOne(carLotId);
        AzProject project = azProjectService.findOne(azProjectId);
        Precondition.checkAjaxArguement(project != null, "0012", "项目不存在");

        if (carLot == null) {
            carLot = new CarLot();
        }
        Precondition.checkAjaxArguement(carLot.getHouseStatus() == null || !carLot.getHouseStatus().equals(2), "0011", "车位已选，不能修改");
        WebUtils.bind(request, carLot);
        carLot.setAzProject(project);
        carLotService.save(carLot);

        Response response = new Response();
        response.setCode("0001");
        response.setData(project.getId());
        return response;
    }


    /**
     * 删除住宅房源
     *
     * @param request
     * @return
     */
    @RequestMapping("deleteCarLot")
    @ResponseBody
    @RequiresPermissions("carLot:deleteCarLot")
    public Response deleteCarLot(HttpServletRequest request) {
        Integer carLotId = ParamUtils.getInt(request, "carLotId", 0);
        CarLot carLot = carLotService.findOne(carLotId);
        Precondition.checkAjaxArguement(carLot != null, "1111", "数据错误！");
        Precondition.checkAjaxArguement(carLot.getHouseStatus() != null && carLot.getHouseStatus() != 2, "1111", "房源已选择，不可删除！");
        this.carLotService.delete(carLot.getId());
        return new Response("0001", "操作成功");
    }


    /**
     * 导入页面
     *
     * @param request
     * @param modelMap
     */
    @RequestMapping("importPage")
    @RequiresPermissions("carLot:importPage")
    public void importPage(HttpServletRequest request, ModelMap modelMap) {
        Integer projectId = ParamUtils.getInt(request, "azProjectId", 0);
        AzProject azProject = this.azProjectService.findOne(projectId);
        Precondition.checkAjaxArguement(azProject != null, "9999", "导入的安置项目不存在");
        Map<String, String> carLotTypeMap = this.dataDictService.getMapByParentNameForName_Value("车位类型");
        modelMap.addAttribute("azProject", azProject);
        modelMap.addAttribute("carLotTypeMap", carLotTypeMap);

    }

    /**
     * 导入车位数据
     *
     * @param request
     * @return
     * @throws Exception
     */
    @Transactional
    @RequestMapping("importCarLot")
    @ResponseBody
    @RequiresPermissions("carLot:importCarLot")
    public Response importStorageRoom(HttpServletRequest request) {
        Integer projectId = ParamUtils.getInt(request, "azProjectId", 0);
        AzProject azProject = this.azProjectService.findOne(projectId);
        Precondition.checkAjaxArguement(azProject != null, "9999", "导入的安置项目不存在");

        String carLots = request.getParameter("carLotArray");
        String[] carLotArray = carLots.split("\r\n");

        //Set<安置项目-幢号-户号-所在层数>
        Set<String> carLotSet = this.carLotService.findCarLotSetByAzProjectId(azProject.getId());

        //buildNum:幢号，houseNum:户号，floor：所在层数，buildArea：建筑面积，carLotType:车位类型，memo：备注
        String buildNum = null, houseNum = null, floor = null, carLotType = null, buildArea = null, memo = null, price = null,zhXbPrice = null,gmXbPrice = null;

        CarLot carLot = null;
        //待导入的车位数据
        List<CarLot> importCarLotList = new ArrayList<>();

        String[] rowObj = null;
        String excelCarLot = null;
        int errorCount = 0;//错误数据数量
        int rowObjLength = 0;//每条数据的列数
        StringBuffer msg = new StringBuffer();
        int index = 0;
        for (String carLotInfo : carLotArray) {
            rowObj = null;
            rowObj = carLotInfo.split("\t");
            rowObjLength = rowObj.length;
            Precondition.checkAjaxArguement(rowObjLength == 9, "0012", "请确认每列都有数据！");
            if (rowObj.length == 0) {
                continue;
            }

            index = 0;
            buildNum = rowObj[index]; //幢号
            index++;
            houseNum = rowObj[index]; //户号
            index++;
            floor = rowObj[index]; //所在层数
            index++;
            carLotType = rowObj[index]; //车位类型
            index++;
            buildArea = rowObj[index]; //产权面积
            index++;
            price = rowObj[index];//单价
            index++;
            memo = rowObj[index];//备注
            index++;
            zhXbPrice = rowObj[index];//车位置换需补交金额
            index++;
            gmXbPrice = rowObj[index];//车位购买续交金额

            excelCarLot = projectId + "-" + buildNum + "-" + houseNum + "-" + floor;

            if (StringUtils.isEmpty(excelCarLot)) {
                continue;
            }
            //只导入不存在的房源
            if (carLotSet.contains(excelCarLot)) {
                errorCount++;
                msg.append("如下：<br/>" + carLotInfo + ",");
                //已经存在的数据输出到页面
                continue;
            }

            carLot = new CarLot();
            carLot.setHouseStatus(Status.NO.getIndex());
            carLot.setAzProject(azProject);
            carLot.setBuildNum(buildNum);
            carLot.setHouseNum(houseNum);
            carLot.setFloor(Integer.valueOf(floor));
            carLot.setCarLotType(Integer.valueOf(carLotType));
            carLot.setBuildArea(BigDecimalUtils.stringToBigDecimal(buildArea));
            carLot.setPrice((BigDecimalUtils.stringToBigDecimal(price)));
            carLot.setMemo(memo);
            carLot.setZhXbPrice(BigDecimalUtils.stringToBigDecimal(zhXbPrice));
            carLot.setGmXbPrice(BigDecimalUtils.stringToBigDecimal(gmXbPrice));
            importCarLotList.add(carLot);
        }
        this.carLotService.batchSave(importCarLotList);
        String successInfo = "插入" + importCarLotList.size() + "条数据;";
        if (errorCount > 0) {
            successInfo = successInfo + "失败" + errorCount + "条，如下：";
        }
        msg = msg.length() == 0 ? msg : msg.replace(0, msg.length(), msg.toString()).append("<br/>数据已存在，无法导入");
        System.out.println(successInfo + msg.toString());
        Response response = new Response("0001", successInfo + msg.toString());
        return response;

    }
}
